package com.usian.admin.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.usian.admin.fegin.ArtivleFegin;
import com.usian.admin.fegin.NewsFegin;
import com.usian.admin.mapper.AdchannelMapper;
import com.usian.admin.mapper.AdsensitiveMapper;
import com.usian.common.fastdfs.FastDFSClientUtil;
import com.usian.common.utis.GreeTextScan;
import com.usian.common.utis.GreenImageScan;
import com.usian.common.utis.SensitiveWordUtil;
import com.usian.model.admin.pojos.AdChannel;
import com.usian.model.admin.pojos.AdSensitive;
import com.usian.model.article.ApAuthor;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmNewss;
import com.usian.model.media.pojos.WmNews;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/news_auth")
public class AdNewsController {
    @Autowired
    private NewsFegin newsFegin;

    @Autowired
    private FastDFSClientUtil fastDFSClientUtil;

    @Autowired
    private ArtivleFegin artivleFegin;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private AdchannelMapper adchannelMapper;

    @Autowired
    private GreeTextScan greeTextScan;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private AdsensitiveMapper adsensitiveMapper;

    @Autowired
    private SensitiveWordUtil sensitiveWordUtil;

    //进行莫提审核查询
    @RequestMapping("list")
    public ResponseResult list(@RequestBody WmNewss wmNews){
        ResponseResult byId = newsFegin.list(wmNews);
        return byId;
    }

    @RequestMapping("findAllByDate")
    public ResponseResult findAllByDate() throws Exception {
        List<WmNews> all = newsFegin.findAll();
        for (WmNews wmNews : all) {
            if(wmNews.getStatus()==8&&wmNews.getPublishTime().getTime()<=System.currentTimeMillis()){
                findByIdNews(wmNews.getId());
                return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
            }
        }
        return null;
    }

    //根据id进行查询进行状态的审核 内容审核
    @RequestMapping("findByIdNews")
    public ResponseResult findByIdNews(Integer id) throws Exception {
        WmNews data = newsFegin.findById(id);
        //判断是否状态为人工审核完成的
        if(data.getStatus()==4){
            artivle_config_content(data);
        }
        //判断是否状态为通过审核但是没发布的
        if(data.getStatus()==8&&data.getPublishTime().getTime()<=System.currentTimeMillis()){
            data.setStatus(9);
            newsFegin.updateNews(data);
            artivle_config_content(data);
        }

        if(data.getStatus()==1){
            //获取文本
            String string = getString(data);
            //获取图片
            List<String> img = getImg(data);
            //自管理敏感词审核
            if(!SensitiveWord(data)){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"敏感词审核失败有敏感词");
            }
            //阿里文本审核
            if(!getgreetext(data, string)){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文本审核失败有敏感词");
            }
            //阿里图片审核
            if(!getgreeimg(data, img)){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"图片审核失败有敏感词");
            }
            if(data.getPublishTime().getTime()>=System.currentTimeMillis()){
                data.setStatus(8);
                newsFegin.updateNews(data);
            }else{
                artivle_config_content(data);
            }

        }
        return null;
    }

    //关键字审核
    public  boolean  SensitiveWord(WmNews wmNews){
        List<AdSensitive> allSensitive = findAllSensitive();
        boolean flag=true;
        List<String> strings = new ArrayList<>();
        for (AdSensitive adSensitive : allSensitive) {
            strings.add(adSensitive.getSensitives());
        }
        sensitiveWordUtil.initMap(strings);
        Map<String, Integer> map = sensitiveWordUtil.matchWords(getString(wmNews));
        if(map.size()>0){
            flag=false;
            wmNews.setStatus(2);
            wmNews.setReason("存在敏感词汇");
            newsFegin.updateNews(wmNews);
        }
        return true;
    }

    //审核文本
    public boolean getgreetext(WmNews data,String str) throws Exception {
        String  msg="";
        boolean flag=true;
        Integer status=0;
        Map map = greeTextScan.greeTextScan(str);
        String suggestion =(String) map.get("suggestion");
        if(suggestion=="pass"){
            status=9;
            msg="审核通过";
            flag=true;
        }else if(suggestion=="abuse"){
            status=2;
            msg="审核未通过,文字统计失败!";
            flag=false;
        }else{
            status=3;
            msg="审核不确定，需要人工审核!";
            flag=false;
        }
        data.setStatus(status);
        data.setReason(msg);
        newsFegin.updateNews(data);
        return flag;
    }

    //审核图片
    public boolean getgreeimg(WmNews data,List<String> str) throws Exception {
        List<byte[]> imageList = new ArrayList<>();
        for (String s : str) {
            String imageName = s.replace("http:///192.168.157.99/", "");
            int i = imageName.indexOf("/");
            String substring = imageName.substring(0, i);
            String substring1 = imageName.substring(i + 1);
            byte[] download = fastDFSClientUtil.download(substring, substring1);
            imageList.add(download);
        }
        boolean flag=true;
        String  msg="";
        Integer status=0;
        Map map =greenImageScan.imageScan(imageList);
        String suggestion =(String) map.get("suggestion");
        if(suggestion=="review"){
            status=3;
            msg="图片无法确定,进行人工审核!";
            flag=false;
        }else if(suggestion=="block"){
            status=2;
            msg="审核未通过,图片审核失败!";
            flag=false;
        }else{
            status=9;
            msg="审核通过";
            flag=true;
        }
        data.setStatus(status);
        data.setReason(msg);
        newsFegin.updateNews(data);
        return flag;
    }

    //获取文本
    public String getString(WmNews data){
        List<Map> maps = JSON.parseArray(data.getContent(), Map.class);
        String str="";
        for (Map map : maps) {
            if(map.get("type").equals("text")){
                str=(String) map.get("value");
            }
        }
        return str;
    }

    //获取图片
    public List<String> getImg(WmNews data){
        List<Map> maps = JSON.parseArray(data.getContent(), Map.class);
        List<String> str = new ArrayList<>();
        for (Map map : maps) {
            if(map.get("type").equals("image")){
                str.add(map.get("value").toString());
            }
        }
        return str;
    }

    //添加中间方法
    public void artivle_config_content(WmNews wmNews) throws IOException {
        com.usian.model.article.pojos.ApArticle apArticle = addApArticle(wmNews);
        addap_article_config(wmNews,apArticle);
        addap_article_content(wmNews,apArticle);
        wmNews.setStatus(9);
        wmNews.setId(wmNews.getId());
        wmNews.setArticleId(apArticle.getId());
        newsFegin.updateNews(wmNews);
    }

    //添加ApArticle表
    public com.usian.model.article.pojos.ApArticle addApArticle(WmNews wmNews) throws IOException {
        //获取用户id查询
        Integer apUserId = wmNews.getUserId();
        //远程调用查询作者名称和id
        ApAuthor allAr = artivleFegin.findAllAr(apUserId);
        com.usian.model.article.pojos.ApArticle apArticle = new com.usian.model.article.pojos.ApArticle();
        apArticle.setAuthorId(allAr.getId().longValue());
        apArticle.setAuthorName(allAr.getName());
        apArticle.setChannelId(wmNews.getChannelId());

        //进行频道name查询
        LambdaQueryWrapper<AdChannel> q = new LambdaQueryWrapper<>();
        q.eq(AdChannel::getId,wmNews.getChannelId());
        AdChannel adChannel = adchannelMapper.selectOne(q);
        apArticle.setChannelName(adChannel.getName());
        apArticle.setTitle(wmNews.getTitle());
        apArticle.setLabels(wmNews.getLabels());
        apArticle.setCreatedTime(wmNews.getCreatedTime());
        apArticle.setPublishTime(wmNews.getPublishTime());
        apArticle.setImages(wmNews.getImages());
        apArticle.setOrigin(false);
        apArticle.setSyncStatus(false);
        //进行ap_articel添加
        apArticle=artivleFegin.add(apArticle);

        IndexRequest indexRequest=new IndexRequest().id(apArticle.getId().toString()).source(apArticle, XContentType.JSON);
        restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        return apArticle;
    }

    //添加ApArticleConfig表
    public void addap_article_config(WmNews wmNews, com.usian.model.article.pojos.ApArticle apArticle){
        com.usian.model.article.pojos.ApArticleConfig apArticleConfig = new com.usian.model.article.pojos.ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setIsDown(false);
        artivleFegin.addArticleConfig(apArticleConfig);
    }

    //添加ApArticleContent表
    public void addap_article_content(WmNews wmNews, com.usian.model.article.pojos.ApArticle apArticle){
        com.usian.model.article.pojos.ApArticleContent apArticleContent = new com.usian.model.article.pojos.ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());
        artivleFegin.addApArticleConfig(apArticleContent);
    }

    //获取敏感词
    public List<AdSensitive> findAllSensitive(){
        List<AdSensitive> adSensitives = adsensitiveMapper.selectList(null);
        return adSensitives;
    }




}
